package com.hh85.sqlite;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {


    private DatabaseUtils databaseUtils;
    private DataAdapter dataAdapter;
    private ArrayList<HashMap<String,String>> datalist;
    private ListView listView;
    private Button keepBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseUtils = new DatabaseUtils(this,"book");
        databaseUtils.open();
        initView();
        loadData();



    }

    private void initView() {

        keepBtn = (Button)findViewById(R.id.id_keep);
        keepBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,KeepActivity.class);
                startActivityForResult(intent,1);
            }
        });
        datalist = new ArrayList<>();
        listView = (ListView)findViewById(R.id.listview);

        dataAdapter = new DataAdapter(MainActivity.this,datalist);
        listView.setAdapter(dataAdapter);


    }

    private void loadData(){
        Cursor cursor =  databaseUtils.select("select * from account",null);

        while(cursor.moveToNext()){
            Integer _id = cursor.getInt(cursor.getColumnIndex("_id"));
            int acid = cursor.getInt(cursor.getColumnIndex("acid"));
            int price = cursor.getInt(cursor.getColumnIndex("price"));
            String remark = cursor.getString(cursor.getColumnIndex("remark"));
            String type = cursor.getString(cursor.getColumnIndex("type"));
            String time = cursor.getString(cursor.getColumnIndex("time"));

            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("_id",_id+"");
            hashMap.put("acid",acid+"");
            hashMap.put("price",price+"");
            hashMap.put("remark",remark);
            hashMap.put("type",type);
            hashMap.put("time",time);
            datalist.add(hashMap);

        }



        dataAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        datalist.clear();
        loadData();
    }
}
